import { TableProps } from 'antd';
import { AnyObject } from 'antd/lib/_util/type';
import { useState } from 'react';

const useTableSelection = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<AnyObject[]>([]);

  const rowSelection: TableProps['rowSelection'] = {
    onSelect: (record: any, selected: any) => {
      console.log('被选中或取消选中的目标行:', record);
      let keys = [...selectedRowKeys];
      if (selected) {
        keys = [...selectedRowKeys, record] as any;
      } else {
        keys = selectedRowKeys.filter((item: any) => item.id !== record.id);
      }
      console.log('当前选中项', keys, 'single');
      setSelectedRowKeys(keys);
    },
    onSelectAll: (selected: any, selectedRows: any, changeRows: any) => {
      console.log(
        selected,
        selectedRows,
        changeRows,
        '是否选中，选中行，改变行',
      );

      if (selected) {
        const addCheckedKeys = changeRows?.map((item: any) => {
          return item;
        });
        setSelectedRowKeys([...selectedRowKeys, ...addCheckedKeys] as any);
      } else {
        const subCheckedKeys = selectedRowKeys.filter((v: any) => {
          return !changeRows.some((item: any) => {
            return item.id === v.id;
          });
        });
        console.log('subCheckedKeys', subCheckedKeys);
        setSelectedRowKeys(subCheckedKeys);
      }
    },

    fixed: true,
    selectedRowKeys: selectedRowKeys?.map((item: any) => item.id),
    columnWidth: 30,
  };
  return {
    selectedRowKeys,
    selectIds: selectedRowKeys?.map((item: any) => item?.id),
    rowSelection,
    setSelectedRowKeys,
  };
};

export default useTableSelection;
